/*
 * @Author: 贺永胜
 * @Date: 2022-06-09 23:38:08
 * @公众号: 百里青山
 * @LastEditors: 贺永胜
 * @LastEditTime: 2022-06-23 18:33:52
 * @Descripttion:
 */
'use strict'

import { app, protocol, BrowserWindow, ipcMain, nativeTheme, Tray, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const path = require('path')
require('@electron/remote/main').initialize()

const isDevelopment = process.env.NODE_ENV !== 'production'

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
}

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

let mainWindow

async function createWindow () {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    icon: path.join(__static, './favicon.png'),
    webPreferences: {
      // preload: path.join(__dirname, './preload.js'),
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      enableRemoteModule: true,
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION
    }
  })
  require('@electron/remote/main').enable(mainWindow.webContents)

  mainWindow.on('close', () => {
    mainWindow = null
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await mainWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) mainWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    mainWindow.loadURL('app://./index.html')

    ipcMain.handle('dark-mode:toggle', () => {
      if (nativeTheme.shouldUseDarkColors) {
        nativeTheme.themeSource = 'light'
      } else {
        nativeTheme.themeSource = 'dark'
      }
      return nativeTheme.shouldUseDarkColors
    })

    ipcMain.handle('dark-mode:system', () => {
      nativeTheme.themeSource = 'system'
    })
  }
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.hide()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// 创建桌面悬浮窗口
const winURL = process.env.NODE_ENV === 'development'
  ? 'http://localhost:8081'
  : 'app://./index.html'
let desktopWindow = null

function createDesktopWindow () {
  desktopWindow = new BrowserWindow({
    width: 500,
    height: 500,
    // frame: false, // 是否显示边缘框
    // fullscreen: true, // 是否全屏显示
    // transparent: true, // 是否透明
    // resizable: false, // 是否可以改变窗口大小
    // type: 'toolbar', // 设置窗口类型为工具窗口，则不会在任务栏出现缩略图
    webPreferences: {
      nodeIntegration: true,
      // 官网似乎说是默认false，但是这里必须设置contextIsolation
      contextIsolation: false
    }
  })

  desktopWindow.loadURL(winURL + '/#/desktop')
  // desktopWindow.setIgnoreMouseEvents(true) // 设置窗口不接收鼠标事件
  desktopWindow.setAlwaysOnTop(false) // 设置窗口置顶
  desktopWindow.on('closed', () => {
    desktopWindow = null
  })
  require('@electron/remote/main').enable(desktopWindow.webContents)
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
  createDesktopWindow()

  // 设置图标及菜单
  const tray = new Tray(path.join(__static, './favicon.png')) // sets tray icon image
  const contextMenu = Menu.buildFromTemplate([ // define menu items
    {
      label: '退出',
      click: () => app.quit()
    }
  ])

  tray.on('click', () => {
    if (!mainWindow) {
      createWindow()
    } else {
      mainWindow.show()
    }
  })
  tray.setContextMenu(contextMenu)
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

ipcMain.on('desktopClose', (e) => { desktopWindow = null })
ipcMain.on('desktopRestar', (e) => {
  desktopWindow.destroy()
  createDesktopWindow()
})
ipcMain.on('showDesktop', (e) => {
  if (desktopWindow) {
    desktopWindow.show()
  } else {
    createDesktopWindow()
  }
})
